package com;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import javax.swing.JFrame;

public class Student extends JFrame{

	private static final long serialVersionUID = 1L;
	private BufferedImage image;
	private DatagramSocket ds;
	public Student() {
		try {
			ds=new DatagramSocket(54123);
			byte[] tmp=new byte[8192];
			DatagramPacket dp=new DatagramPacket(tmp, tmp.length);
			new Thread(){
				@Override
				public void run() {
					int a=0;
					while(true){
						try {
							ByteArrayOutputStream out=new ByteArrayOutputStream();							
							while (true) {
								ds.receive(dp);
								String mess = new String(dp.getData(), 0, dp.getLength());
								if(mess.equals("end"))break;
								//System.out.println("==>"+dp.getLength());
								out.write(tmp, 0, dp.getLength());
							}
							//System.out.println("=======================================");
							byte[] imgb=out.toByteArray();
							InputStream in=new ByteArrayInputStream(imgb);
							image=ImageIO.read(in);
							a++;
							File file=new File("c:\\p"+a+".png");
							ImageIO.write(image, "png", file);
							repaint();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}.start();
			this.setUndecorated(true); // 全屏显示
			GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(this);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
	
	@Override
	public void paint(Graphics g) {
		Graphics2D g2=(Graphics2D) g;
        g2.drawImage(image, 0, 0, this); 		
	}	
	@Override
	public void update(Graphics g) {
		Graphics gBuffer=image.getGraphics();//获得图片缓冲区的画笔
        if(gBuffer!=null)
            paint(gBuffer);
        else
            paint(g);
        gBuffer.dispose();
        g.drawImage(image, 0, 0,null);
	}
	
	public static void main(String[] args) {
		new Student();
	}
}
